<?php
// +----------------------------------------------------------------------
// | Description: 合同
// +----------------------------------------------------------------------
// | Author:  Michael_xu | gengxiaoxu@5kcrm.com
// +----------------------------------------------------------------------
namespace app\crm\model;

use think\Db;
use app\admin\model\Common;
use think\Request;
use think\Validate;

class Invoicing extends Common
{
	/**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
	protected $name = 'crm_invoicing';
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
	protected $autoWriteTimestamp = true;
	/**
     * [getDataList 合同list]
     * @author Michael_xu
     * @param     [string]                   $map [查询条件]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [每页数量]
     * @return    [array]                    [description]
     */		
	public function getDataList($request)
    {
        $userModel = new \app\admin\model\User();
        $user_id = $request['user_id'];
        if(isset($request["contract_id"]) && !empty($request["contract_id"]))
        {
            $map=["invoicing.contract_id"=>$request["contract_id"]];
        }
        $list = db('crm_invoicing')
            ->alias('invoicing')
            ->join('__CRM_CUSTOMER__ customer','invoicing.customer_id = customer.customer_id','LEFT')
            ->join('__CRM_CONTRACT__ contract','invoicing.contract_id = contract.contract_id','LEFT')
            ->where($map)
            ->limit(($request['page']-1)*$request['limit'], $request['limit'])
            ->field('invoicing.*,customer.name as customer_name,contract.name as contract_name')
            /*->order("invoicing.createtime","desc")
            ->group('invoicing.id')*/
            ->select();
        $dataCount = db('crm_invoicing')
            ->alias('invoicing')
            ->join('__CRM_CUSTOMER__ customer','invoicing.customer_id = customer.customer_id','LEFT')
            ->join('__CRM_CONTRACT__ contract','invoicing.contract_id = contract.contract_id','LEFT')
            ->where($map)
            ->count('invoicing.invoicing_id');

        $data = [];
        $data['list'] = $list;
        $data['dataCount'] = $dataCount ? : 0;
        return $data;
    }

	//根据IDs获取数组
	public function getDataByStr($idstr)
	{
		$idArr = stringToArray($idstr);
		if (!$idArr) {
			return [];
		}
		$list = Db::name('CrmContract')->where(['invoicing_id' => ['in',$idArr]])->select();
		return $list;
	}
	
	/**
	 * 创建开票申请
	 * @author Michael_xu
	 * @param  
	 * @return                            
	 */	
	public function createData($param)
	{
		$fieldModel = new \app\admin\model\Field();
		$userModel = new \app\admin\model\User();
		$productModel = new \app\crm\model\Product();
		// 自动验证
		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
		$validate = new Validate($validateArr['rule'], $validateArr['message']);
		$contractModel=new Contract();
        $contract=$contractModel->field("customer_id")->where(["contract_id"=>$param["contract_id"]])->find();
        $param["customer_id"]=empty($contract["customer_id"])?0:$contract["customer_id"];
		$result = $validate->check($param);
		if (!$result) {
			$this->error = $validate->getError();
			return false;
		}		

		//处理部门、员工、附件、多选类型字段
		/*$arrFieldAtt = $fieldModel->getArrayField('crm_invoicing');
		foreach ($arrFieldAtt as $k=>$v) {
			$param[$v] = arrayToString($param[$v]);
		}*/

		if ($this->data($param)->allowField(true)->save()) {
            //站内信
           /* $createUserInfo = $userModel->getDataById($param['create_user_id']);
            $send_user_id = stringToArray($param['check_user_id']);
            $sendContent = $createUserInfo['realname'].'提交了合同【'.$param['name'].'】,需要您审批';
            if ($send_user_id) {
            	sendMessage($send_user_id, $sendContent, $this->invoicing_id, 1);
            }*/
			$data = [];
			$data['invoicing_id'] = $this->invoicing_id;
			return $data;
		} else {
			$this->error = '添加失败';
			return false;
		}			
	}

	/**
	 * 编辑开票
	 * @author Michael_xu
	 * @param  
	 * @return                            
	 */	
	public function updateDataById($param, $invoicing_id = '')
	{
		/*$productModel = new \app\crm\model\Product();
		$userModel = new \app\admin\model\User();
		$dataInfo = db('crm_invoicing')->where(['invoicing_id' => $invoicing_id])->find();
		//过滤不能修改的字段
		$unUpdateField = ['create_user_id','is_deleted','delete_time'];
		foreach ($unUpdateField as $v) {
			unset($param[$v]);
		}
		$param['invoicing_id'] = $invoicing_id;
		$fieldModel = new \app\admin\model\Field();
		// 自动验证
		$validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
		$validate = new Validate($validateArr['rule'], $validateArr['message']);

		$result = $validate->check($param);
		if (!$result) {
			$this->error = $validate->getError();
			return false;
		}

		//处理部门、员工、附件、多选类型字段
		$arrFieldAtt = $fieldModel->getArrayField('crm_invoicing');
		foreach ($arrFieldAtt as $k=>$v) {
			$param[$v] = arrayToString($param[$v]);
		}*/

		if ($this->allowField(true)->save($param, ['invoicing_id' => $invoicing_id])) {
			//产品数据处理
	       /* $resProduct = $productModel->createObject('crm_invoicing', $param, $invoicing_id);
			//修改记录
			updateActionLog($param['user_id'], 'crm_invoicing', $invoicing_id, $dataInfo, $param);
			//站内信
            $createUserInfo = $userModel->getDataById($param['user_id']);
            $send_user_id = stringToArray($param['check_user_id']);
            $sendContent = $createUserInfo['realname'].'提交了合同【'.$param['name'].'】,需要您审批';
            if ($send_user_id) {
            	sendMessage($send_user_id, $sendContent, $invoicing_id, 1);
            }*/
			$data = [];
			$data['invoicing_id'] = $invoicing_id;
			return $data;
		} else {
			$this->error = '编辑失败';
			return false;
		}					
	}

	/**
     * 开票申请数据
     * @param  $id 合同ID
     * @return 
     */	
   	public function getDataById($id = '')
   	{   
   		$receivablesModel = new \app\crm\model\Receivables();
   		$userModel = new \app\admin\model\User();	
   		$map['invoicing_id'] = $id;
		$dataInfo = $this->where($map)->find();
		if (!$dataInfo) {
			$this->error = '暂无此数据';
			return false;
		}
		$dataInfo['create_user_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
		/*$dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
		$dataInfo['business_id_info'] = $dataInfo['business_id'] ? db('crm_business')->where(['business_id' => $dataInfo['business_id']])->field('business_id,name')->find() : [];
        */
		$dataInfo['customer_id_info'] = $dataInfo['customer_id'] ? db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name')->find() : [];
        //回款金额
       /* $receivablesMoney = $receivablesModel->getMoneyByContractId($id);
        $dataInfo['receivablesMoney'] = $receivablesMoney ? : [];*/
		return $dataInfo;
   	}
   	/**
   	 * 删除开票
   	 * */
   	public function delDatas($ids)
    {
        if (empty($ids)) {
            $this->error = '删除失败';
            return false;
        }
        try {
            $this->where($this->getPk(), 'in', $ids)->delete();
            return true;
        } catch (\Exception $e) {
            $this->error = '操作失败';
            return false;
        }
    }


}